import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorage } from '@core/local.storage';
import { Router } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { TreeTools } from '@core/treeTools.tool';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-operamodal',
    templateUrl: './operaModal.component.html',
    styleUrls: ['./signalProblem.component.less']
})
export class OperaModalComponent implements OnInit {
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() width: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    thisData: any = { 'count': 0, 'id': [] };

    detailObj: any = { 'class': 'packup', 'text': '详情展开' };
    gzxmList = [];
    jcbmNodes = [];
    jcbmList = [];
    jcddAutoData = [];
    jcddTempData = [];
    zrbmNodes = [];
    zrbmList = [];
    wtlbNodes = [];
    wtlbList = [];
    czNodes = [];
    czList = [];
    sblxNodes = [];
    sblxList = [];
    sbmcNodes = [];
    tbzrbmNodes = [];
    xfzrbmNodes = [];
    wtxxInfo = '';
    zrbmInfo = '';
    treeNodeStyle = { 'max-height': '300px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    wtlbCompareFn = (o1: any, o2: any) => (o1 && o2 ? o1.code === o2.code : o1 === o2);
    tbzrbmCompareFn = (o1: any, o2: any) => (o1 && o2 ? o1.ID === o2.ID : o1 === o2);

    constructor(
        private msg: NzMessageService,
        public ls: LocalStorage,
        private datePipe: DatePipe,
        private router: Router,
        public treeTools: TreeTools,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        if (!this.width) {
            this.width = '500';
        }
        switch (this.operaType) {
            case 'add':
                this.getOperaApi('update', () => {
                    const loginInfo = JSON.parse(this.ls.get('loginInfo'));
                    this.operaData.checkOrgId = loginInfo.VC_ORG$ID;
                    this.operaData.chargeOrgId = loginInfo.VC_ORG$ID;
                    this.operaData.checkPerson = loginInfo.VC_NAME;
                    this.operaData.checkDate = new Date();
                });
                break;
            case 'edit':
                let updateStatus = false;
                let updateCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        updateCount += 1;
                        this.objData = item;
                        updateStatus = true;
                    }
                }
                if (updateStatus && updateCount === 1) {
                    this.getOperaApi('update', () => {
                        // 回填数据
                        this.getProjects(this.objData.id, (results) => {
                            this.operaData.id = this.objData.id;
                            this.operaData.gzxm = [];
                            for (const item of results) {
                                this.operaData.gzxm.push(item.projectId);
                                for (const data of this.gzxmList) {
                                    if (data.code === item.projectId) {
                                        data.checked = true;
                                    }
                                }
                            }
                            this.operaData.checkOrgId = this.objData.checkOrgId;
                            this.operaData.chargeOrgId = this.objData.chargeOrgId;
                            this.operaData.checkDate = this.objData.checkDate;
                            this.operaData.checkPlace = this.objData.checkPlace;
                            this.operaData.checkPerson = this.objData.checkPerson;
                            this.operaData.problemDesc = this.objData.problemDesc;
                            this.operaData.handleRequire = this.objData.handleRequire;
                            this.operaData.deadline = this.objData.deadline;
                            this.operaData.typeId = { code: this.objData.typeId, name: this.objData.typeName };
                            this.operaData.remark = this.objData.remark;
                            this.operaData.stationId = this.objData.stationId;
                            // 车站-类型-设备
                            this.czChange(this.operaData.stationId, () => {
                                this.operaData.devTypeCode = this.objData.devTypeCode;
                                this.lxChange(this.operaData.devTypeCode, () => {
                                    if (this.objData.devId) {
                                        this.operaData.devId = this.objData.devId.split(',');
                                    }
                                });
                            });
                        });
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'del':
                let delStatus = false;
                for (const item of this.responseData) {
                    if (item.checked) {
                        this.objData = item;
                        this.thisData.count += 1;
                        this.thisData.id.push(item.id);
                        delStatus = true;
                    }
                }
                if (delStatus) {
                    this.getOperaApi('del', () => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择数据进行操作');
                }
                break;
            case 'tb':
            case 'aqktb':
                let tbStatus = false;
                let tbCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        tbCount += 1;
                        this.objData = item;
                        tbStatus = true;
                    }
                }
                if (tbStatus && tbCount === 1) {
                    this.getOperaApi('tb', () => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'xf':
                let xfStatus = false;
                let xfCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        xfCount += 1;
                        this.objData = item;
                        xfStatus = true;
                    }
                }
                if (xfStatus && xfCount === 1) {
                    this.getOperaApi('xf', () => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'zyhk':
                let zyhkStatus = false;
                let zyhkCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        zyhkCount += 1;
                        this.objData = item;
                        zyhkStatus = true;
                    }
                }
                if (zyhkStatus && zyhkCount === 1) {
                    this.getOperaApi('', () => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'qs':
            case 'sqxh':
            case 'wcrw':
            case 'zgwt':
            case 'sqyq':
            case 'pz':
            case 'aqkpz':
            case 'bh':
            case 'aqkbh':
            case 'tyyq':
            case 'bhyq':
                let qsStatus = false;
                let qsCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        qsCount += 1;
                        this.objData = item;
                        this.thisData.count += 1;
                        qsStatus = true;
                    }
                }
                if (qsStatus && qsCount === 1) {
                    this.getOperaApi('', () => {
                        this.wtxxInfo = this.objData.problemDesc;
                        this.zrbmInfo = this.objData.chargeOrgName;
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
        }
    }
    getOperaApi(type, callback) {
        setTimeout(() => {
            this.Visible = true;
            switch (type) {
                case 'update':// 包含add和edit
                    const updateApi = [
                        this.http.get(environment.project + '/sysTDict/getDictByClass?code=SAFE_PROBLEM_PROJECT'),
                        this.http.get(environment.apiBase + '/csmis/getKmnOrgTree.jwt?showAll=1&showSeg=1'),
                        this.http.get(environment.project + '/sysTDict/getDictByClass?code=SAFE_PROBLEM_TYPE'),
                        this.http.get(environment.apiBase + '/csmis/publicTree/getorgstatree.jwt')
                    ];
                    forkJoin(updateApi).subscribe((results: any) => {
                        if (!results[0].code) {
                            this.gzxmList = results[0].data;
                        }
                        if (results[1]) {
                            Object.assign(this.jcbmNodes, results[1]);
                            this.childToList(this.jcbmList, results[1]);
                            Object.assign(this.zrbmNodes, results[1]);
                            this.childToList(this.zrbmList, results[1]);
                        }
                        if (!results[2].code) {
                            this.wtlbNodes = results[2].data;
                        }
                        if (results[3]) {
                            this.czNodes = this.treeTools.formatTreeNode(results[3]);
                            this.childToList(this.czList, results[3]);
                            this.autoToList(this.jcddTempData, results[3]);
                        }
                        if (callback) {
                            callback()
                        }
                    });
                    break;
                case 'del':
                    if (callback) {
                        callback()
                    }
                    break;
                case 'tb':
                case 'aqktb':
                    const tbApi = [
                        this.http.get(environment.project + '/sysTOrg/getSelfAndParOrgs')
                    ];
                    forkJoin(tbApi).subscribe((results: any) => {
                        if (!results[0].code) {
                            this.tbzrbmNodes = results[0].data;
                        }
                        if (callback) {
                            callback()
                        }
                    });
                    break;
                case 'xf':
                    const xfApi = [
                        this.http.get(environment.project + '/sysTOrg/getChildsOrgs')
                    ];
                    forkJoin(xfApi).subscribe((results: any) => {
                        if (!results[0].code) {
                            this.xfzrbmNodes = results[0].data;
                        }
                        if (callback) {
                            callback()
                        }
                    });
                    break;
                default:
                    if (callback) {
                        callback()
                    }
                    break;
            }
        }, 200);
    }
    deadlineChange(e) {
        if (e.getTime() - this.operaData.checkDate.getTime() < 0) {
            this.msg.error('整改时限不能早于检查时间');
            setTimeout(() => {
                this.operaData.deadline = this.operaData.checkDate;
            }, 500);
        }
    }
    // 通过问题库id获取项目
    getProjects(id, callback) {
        this.http.get(environment.project + '/safeProblem/getProjectsByPid?id=' + id).subscribe((results: any) => {
            if (!results.code) {
                if (callback) {
                    callback(results.data);
                }
            }
        });
    }
    czChange(e, callback?) {
        this.sblxNodes = [];
        this.sblxList = [];
        if (e) {
            const url = environment.apiBase + '/csmis/devTypes/getAllTypesByStaId1.jwt?station=' + e;
            this.http.get(url).subscribe((res: any) => {
                this.sblxNodes = this.treeTools.formatTreeNode(res);
                this.childToList(this.sblxList, this.sblxNodes);
                if (callback) {
                    callback();
                }
            });
        }
    }
    lxChange(e, callback?) {
        this.sbmcNodes = [];
        const url = environment.apiBase + '/csmis/publicTree/getDevByStationType.jwt?staid=' + this.operaData.stationId + '&typeid=' + e;
        this.http.get(url).subscribe((res: any) => {
            if (res.type === "success" && res.response.data) {
                this.sbmcNodes = res.response.data;
                if (callback) {
                    callback();
                }
            }
        });
    }
    gzxmChange(e) {
        this.operaData.gzxm = e;
    }
    // children转list
    childToList(array, list) {
        list.forEach(item => {
            array.push(item);
            if (item.children && item.children.length) {
                this.childToList(array, item.children);
            }
        })
    }
    // children转list
    autoToList(array, list) {
        list.forEach(item => {
            array.push(item.text);
            if (item.children && item.children.length) {
                this.autoToList(array, item.children);
            }
        })
    }
    detail() {
        if (this.detailObj.class === 'packup') {
            this.detailObj.class = 'packout';
            this.detailObj.text = '详情收起';
        } else {
            this.detailObj.class = 'packup';
            this.detailObj.text = '详情展开';
        }
    }
    jcddInput(e) {
        const value = e.target.value;
        switch (value) {
            case '':
            case null:
            case undefined:
                this.jcddAutoData = [];
                break;
            default:
                this.jcddAutoData = this.jcddTempData.filter(option => option.indexOf(value) !== -1);
                break;
        }
    }
    Ok() {
        let param: any = {};
        switch (this.operaType) {
            case 'add':
            case 'edit':
                if (!this.operaData.gzxm || !this.operaData.gzxm.length) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                    return;
                }
                if (!this.operaData.checkOrgId || !this.operaData.checkDate || !this.operaData.checkPlace
                    || !this.operaData.checkPerson || !this.operaData.problemDesc || !this.operaData.handleRequire
                    || !this.operaData.deadline || !this.operaData.chargeOrgId || !this.operaData.typeId
                ) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                }
                Object.assign(param, this.operaData);
                if (this.operaType === 'edit') {
                    param.id = this.operaData.id;
                }
                if (param.typeId) {
                    param.typeName = param.typeId.name;
                    param.typeId = param.typeId.code;
                }
                param.checkDate = this.datePipe.transform(param.checkDate, 'yyyy-MM-dd');
                param.deadline = this.datePipe.transform(param.deadline, 'yyyy-MM-dd');
                param.projectName = [];
                // 根据ID取NAME
                for (const item of this.gzxmList) {
                    for (const data of param.gzxm) {
                        if (data === item.code) {
                            param.projectName.push(item.name);
                        }
                    }
                }
                param.projectName = param.projectName.join(',');
                param.projectId = param.gzxm.join(',');
                param.devName = [];
                if (param.devId) {
                    param.devId = this.operaData.devId.join(',');
                    for (const item of this.operaData.devId) {
                        for (const data of this.sbmcNodes) {
                            if (data.ID === item) {
                                param.devName.push(data.VC_NAME)
                            }
                        }
                    }
                }
                if (param.devName) {
                    param.devName = param.devName.join(',');
                    for (const item of this.jcbmList) {
                        if (item.key === param.checkOrgId) {
                            param.checkOrgName = item.title;
                            break;
                        }
                    }
                }
                for (const item of this.zrbmList) {
                    if (item.key === param.chargeOrgId) {
                        param.chargeOrgName = item.title;
                        break;
                    }
                }
                for (const item of this.czList) {
                    if (item.id === param.stationId) {
                        param.stationName = item.text;
                        break;
                    }
                }
                for (const item of this.sblxList) {
                    if (item.key === param.devTypeCode) {
                        param.devTypeName = item.title;
                        break;
                    }
                }
                delete param.gzxm;
                break;
            case 'del':
                param = this.thisData.id;
                break;
            case 'tb':
            case 'aqktb':
                if (!this.operaData.tbOrgId) {
                    this.msg.error('请选择部门', { nzDuration: 1000 });
                    return;
                }
                param = new FormData();
                param.append('id', this.objData.id);
                param.append('orgName', this.operaData.tbOrgId.NAME);
                param.append('orgId', this.operaData.tbOrgId.ID);
                break;
            case 'xf':
                if (!this.operaData.xfOrgId) {
                    this.msg.error('请选择部门', { nzDuration: 1000 });
                    return;
                }
                param = new FormData();
                param.append('id', this.objData.id);
                param.append('orgName', this.operaData.xfOrgId.NAME);
                param.append('orgId', this.operaData.xfOrgId.ID);
                break;
            case 'qs':
            case 'sqxh':
            case 'wcrw':
                param = new FormData();
                param.append('id', this.objData.id);
                break;
            case 'zgwt':
                if (!this.operaData.zgwt) {
                    this.msg.error('请填整改内容', { nzDuration: 1000 });
                    return;
                }
                param = new FormData();
                param.append('id', this.objData.id);
                param.append('info', this.operaData.zgwt);
                break;
            case 'sqyq':
                if (!this.operaData.sqyq) {
                    this.msg.error('请选择延期日期', { nzDuration: 1000 });
                    return;
                }
                param = new FormData();
                param.append('id', this.objData.id);
                param.append('delayDate', this.datePipe.transform(this.operaData.sqyq, 'yyyy-MM-dd'));
                break;
            case 'pz':
            case 'aqkpz':
            case 'bh':
            case 'aqkbh':
            case 'tyyq':
            case 'bhyq':
                if (!this.operaData.yj) {
                    this.operaData.yj = '';
                }
                param = new FormData();
                param.append('id', this.objData.id);
                param.append('advice', this.operaData.yj);
                break;
            case 'zyhk':
                param = this.objData;
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.router.navigate(['safeHiddenDanger'], { queryParams: param });
                }, 200);
                return;
        }
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                }, 200);
            } else {
                if (res.msg) {
                    this.msg.error(res.msg);
                } else {
                    this.msg.error('操作失败');
                }
            }
        });
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
        }, 200);
    }
}